package com.nine.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nine.common.entity.*;
import com.nine.common.tool.ResponseResult;
import com.nine.system.mapper.*;
import com.nine.system.service.MoneyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

@Service
public class MoneyServiceImpl implements MoneyService {
    @Autowired
    private MoneyMapper moneyMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EngineerMapper engineerMapper;


    @Override
    public ResponseResult findSome(String sysId, Date date1, Date date2) {

        LambdaQueryWrapper<MoneyLogForm> moneywrapper = new LambdaQueryWrapper<>();

        long uid = StpUtil.getLoginIdAsLong();
        //101 平台 102 商家 103 工程师
        int roleId = userInfoMapper.selectById(uid).getRoleId();

        if(roleId==101){
            long id=1;
            if(sysId!=null && !sysId.isEmpty()) id = Long.parseLong(sysId);
            moneywrapper.eq(MoneyLogForm::getSysId,id);
        }else if(roleId==102||roleId==103){
            moneywrapper.eq(MoneyLogForm::getSysId,uid);
        }

        moneywrapper.between(MoneyLogForm::getLogTime,date1,date2);



        List<MoneyLogForm> list = moneyMapper.selectList(moneywrapper);

        BigDecimal[] money = new BigDecimal[(int) getpos(date1,date2)+1];
            for (int i = 0; i < money.length; i++) {
                money[i]=new BigDecimal(0);
            }
        int[] num = new int[(int) getpos(date1,date2)+1];
        //总单量，总钱数
        long allnum=0;
        BigDecimal allmoney=new BigDecimal(0);
        //最大单量，最大钱
        long maxnum=0;
        BigDecimal maxmmoney=new BigDecimal(0);

        for (int i=0;i<list.size();i++){
            MoneyLogForm moneyLogForm = list.get(i);
            int pos= (int) getpos(date1,moneyLogForm.getLogTime());
            allmoney=allmoney.add(moneyLogForm.getMoney().abs());
            allnum++;
            money[pos]=money[pos].add(moneyLogForm.getMoney().abs());
            num[pos]++;
        }

        for (int i = 0; i < getpos(date1,date2); i++) {
            if(num[i]>maxnum) maxnum=num[i];
            //大于
            if(money[i].compareTo(maxmmoney)>0) maxmmoney=money[i];
        }

        long resmaxnum=maxnum-maxnum%20+20;
        long resmaxmoney=maxmmoney.longValue()-maxmmoney.longValue()%100+100;

        ArrayList<Object> objects = new ArrayList<>();

        objects.add(money);
        objects.add(num);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String date1s = df.format(date1);
        String date2s = df.format(date2);
        objects.add(getBetweenDate(date1s,date2s));

        objects.add(allmoney);
        objects.add(allnum);
        objects.add(resmaxnum);
        objects.add(resmaxmoney);

        return ResponseResult.ok(objects);
    }

    private long getpos(Date date1, Date date2) {
        // 创建两个LocalDate对象
        LocalDate startDate = date1.toLocalDate();
        LocalDate endDate = date2.toLocalDate();

        // 使用ChronoUnit.DAYS计算它们之间相差的天数
        long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);

        return daysBetween;
    }

    public static long getpos(Date date1, LocalDateTime date2) {

        // 创建两个LocalDate对象
        LocalDate startDate = date1.toLocalDate();
        LocalDate endDate = date2.toLocalDate();

        // 使用ChronoUnit.DAYS计算它们之间相差的天数
        long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);

        return daysBetween;
    }

    public static List<String> getBetweenDate(String startTime, String endTime){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 声明保存日期集合
        List<String> list = new ArrayList<String>();
        try {
            // 转化成日期类型
            java.util.Date startDate = sdf.parse(startTime);
            java.util.Date endDate = sdf.parse(endTime);

            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime()<=endDate.getTime()){
                // 把日期添加到集合
                list.add(sdf.format(startDate));
                // 设置日期
                calendar.setTime(startDate);
                //把日期增加一天
                calendar.add(Calendar.DATE, 1);
                // 获取增加后的日期
                startDate=calendar.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }

    public ResponseResult findOne(String orderId) {

        long touid = StpUtil.getLoginIdAsLong();
        LambdaQueryWrapper<UserInfo> towrapper= new LambdaQueryWrapper<>();
        towrapper.eq(UserInfo::getUid,touid);
        int toroleId = userInfoMapper.selectOne(towrapper).getRoleId();


        LambdaQueryWrapper<MoneyLogForm> moneywrapper = new LambdaQueryWrapper<>();

        long id=0L;
        if(orderId!=null && !orderId.isEmpty()){
            id = Long.parseLong(orderId);
            moneywrapper.eq(MoneyLogForm::getOrderId,id);
        }

        List<MoneyLogForm> list = moneyMapper.selectList(moneywrapper);

        List<MoneyLogFormVO> result=new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            MoneyLogForm moneyLogForm = list.get(i);

//            long orderId=moneyLogForm.getOrderId();
            LambdaQueryWrapper<OrderForm> orderwrapper = new LambdaQueryWrapper<>();
            orderwrapper.eq(OrderForm::getOrderId,id);
            OrderForm orderForm = orderMapper.selectOne(orderwrapper);
            Date orderDate = orderForm.getOrderDate();
            Integer orderTime = orderForm.getOrderTime();

            long sysId=moneyLogForm.getSysId();
            String sysName=null;
            LambdaQueryWrapper<UserInfo> userInfowrapper = new LambdaQueryWrapper<>();
            userInfowrapper.eq(UserInfo::getUid,sysId);
            UserInfo userInfo = userInfoMapper.selectOne(userInfowrapper);
            int roleId = userInfo.getRoleId();
            if(roleId==101){
                sysName="平台";
            } else if (roleId==102){
                LambdaQueryWrapper<UserForm> userwrapper = new LambdaQueryWrapper<>();
                userwrapper.eq(UserForm::getUserId,sysId);
                sysName = userMapper.selectOne(userwrapper).getUserName();
            } else if (roleId==103){
                LambdaQueryWrapper<EngineerForm> engineerwrapper = new LambdaQueryWrapper<>();
                engineerwrapper.eq(EngineerForm::getEngineerId,sysId);
                sysName = engineerMapper.selectOne(engineerwrapper).getEngineerName();
            }

            System.out.println(moneyLogForm.getSysId());

            if(toroleId==101)
                result.add(new MoneyLogFormVO(moneyLogForm,orderDate,orderTime,sysName));
            else if (moneyLogForm.getSysId()==touid) {
                result.add(new MoneyLogFormVO(moneyLogForm,orderDate,orderTime,sysName));
            }
            System.out.println(result);
        }

        return ResponseResult.ok(result);
    }

    @Override
    public ResponseResult getBalanceBy102() {
        long uid = StpUtil.getLoginIdAsLong();

        BigDecimal balance = userInfoMapper.selectById(uid).getBalance();
        return ResponseResult.ok(balance);
    }

    @Override
    public ResponseResult getBalanceBy103() {
        long uid = StpUtil.getLoginIdAsLong();
        BigDecimal balance = userInfoMapper.selectById(uid).getBalance();

        return ResponseResult.ok(balance);
    }

    @Override
    public ResponseResult getBalanceBy101() {
        long uid = StpUtil.getLoginIdAsLong();
        BigDecimal balance = userInfoMapper.selectById(uid).getBalance();

        return ResponseResult.ok(balance);

    }
}
